<template>
  <view class="consult-create-page">
    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 问题类型选择 -->
      <view class="form-group">
        <text class="form-label">问题类型（可多选）</text>
        <view class="problem-type-list">
          <view 
            v-for="type in questionTypes" 
            :key="type.value"
            class="type-item"
            :class="{ active: formData.selectedTypes.includes(type.value) }"
            @click="selectType(type.value)"
          >
            <text class="type-text">{{ type.label }}</text>
          </view>
        </view>
        
        <!-- 类型说明 -->
        <text class="description-text">{{ combinedDescription }}</text>
      </view>
      
      <!-- 问题描述 -->
      <view class="form-group">
        <text class="form-label">详细描述</text>
        <textarea 
          class="form-textarea"
          v-model="formData.description"
          placeholder="请详细描述您遇到的问题，包括症状、时间、相关情况等"
          maxlength="500"
        />
        <text class="char-count">{{ formData.description.length }}/500</text>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-section">
      <button 
        class="submit-button"
        :class="{ disabled: !canSubmit }"
        :disabled="!canSubmit"
        @click="submitConsult"
      >
        提交咨询
      </button>
    </view>
  </view>
</template>

<script>
import consultConfig from '@/static/config/consult_config.json'

export default {
  name: "ConsultCreate",
      data() {
        return {
          formData: {
            selectedTypes: [], // 改为数组支持多选
            description: ''
          },
          questionTypes: [],
          selectedDescription: '点击标签可以查看类型说明',
          isSubmitting: false
        };
      },
  computed: {
    canSubmit() {
      return this.formData.selectedTypes.length > 0 && 
             this.formData.description.trim() &&
             !this.isSubmitting;
    },
    // 获取所有选中类型的说明文本
    combinedDescription() {
      if (this.formData.selectedTypes.length === 0) {
        return '点击标签可以查看类型说明';
      }
      
      const descriptions = this.formData.selectedTypes.map(typeValue => {
        const config = this.questionTypes.find(item => item.value === typeValue);
        return config ? `${config.label}：${config.description}` : '';
      }).filter(desc => desc);
      
      if (descriptions.length === 1) {
        return descriptions[0];
      } else if (descriptions.length > 1) {
        return descriptions.join('\n');
      }
      
      return '点击标签可以查看类型说明';
    }
  },
  mounted() {
    this.loadQuestionTypes();
  },
  methods: {
    // 加载问题类型配置
    loadQuestionTypes() {
      if (consultConfig && consultConfig.question_types) {
        this.questionTypes = Object.entries(consultConfig.question_types).map(([key, config]) => ({
          value: key,
          label: config.cn,
          expert_type: config.expert_type,
          description: config.description
        }));
      }
    },
    
    // 选择问题类型（支持多选）
    selectType(type) {
      const index = this.formData.selectedTypes.indexOf(type);
      if (index > -1) {
        // 如果已选中，则取消选择
        this.formData.selectedTypes.splice(index, 1);
      } else {
        // 如果未选中，则添加选择
        this.formData.selectedTypes.push(type);
        // 按照questionTypes的显示顺序排序
        this.formData.selectedTypes.sort((a, b) => {
          const indexA = this.questionTypes.findIndex(item => item.value === a);
          const indexB = this.questionTypes.findIndex(item => item.value === b);
          return indexA - indexB;
        });
      }
    },
    
    // 提交咨询
    async submitConsult() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善信息',
          icon: 'none'
        });
        return;
      }
      
      this.isSubmitting = true;
      uni.showLoading({
        title: '提交中...',
        mask: true
      });
      
      try {
        // 获取选中的专家类型名称（去重）
        const expertTypes = this.formData.selectedTypes.map(typeValue => {
          const config = this.questionTypes.find(item => item.value === typeValue);
          return config ? config.expert_type : '';
        }).filter(type => type);
        
        // 去重
        const uniqueExpertTypes = [...new Set(expertTypes)];
        
        if (uniqueExpertTypes.length === 0) {
          throw new Error('未找到选中的专家类型');
        }
        
        // 获取选中的问题类型（用户选择的问题类型标签）
        const questionTypes = this.formData.selectedTypes.map(typeValue => {
          const config = this.questionTypes.find(item => item.value === typeValue);
          return config ? config.value : '';
        }).filter(type => type);
        
        const consultData = {
          expert_types_names: uniqueExpertTypes,
          question_types: questionTypes,
          description: this.formData.description.trim()
        };
        
        console.log('提交咨询数据:', consultData);
        
        // 调用后端接口创建咨询
        const response = await this.$request({
          url: '/consultation/ticket/create/',
          method: 'POST',
          data: consultData
        });
        
        if (response.statusCode === 201) {
          uni.hideLoading();
          uni.showToast({
            title: '咨询创建成功',
            icon: 'success'
          });
          
          // 延迟跳转到工单详情页
          setTimeout(() => {
            // 跳转到工单详情页，传递工单ID
            uni.redirectTo({
              url: `/sub_pages/pages/consult_detail/consult_detail?ticketId=${response.data.id}`
            });
          }, 500);
        } else {
          throw new Error(response.data?.error || '创建失败');
        }
        
      } catch (error) {
        uni.hideLoading();
        this.isSubmitting = false;
        console.error('创建咨询失败:', error);
        uni.showToast({
          title: error.message || '创建失败，请重试',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style scoped>
.consult-create-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  padding: 20rpx 0;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  margin-top: 20rpx;
}

.form-group {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
}

.form-label {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.problem-type-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.type-item {
  padding: 16rpx 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 24rpx;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.type-item.active {
  border-color: #007bff;
  background-color: #e7f3ff;
}

.type-text {
  font-size: 28rpx;
  color: #333;
}

.type-item.active .type-text {
  color: #007bff;
  font-weight: bold;
}

.description-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.8;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border-left: 4rpx solid #007bff;
  margin-top: 20rpx;
  display: block;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
}

.form-input:focus {
  border-color: #007bff;
  background-color: white;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  max-height: 400rpx;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
  resize: none;
  box-sizing: border-box;
}

.form-textarea:focus {
  border-color: #007bff;
  background-color: white;
}

.char-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-top: 10rpx;
  display: block;
}

.submit-section {
  padding: 40rpx 20rpx;
}

.submit-button {
  width: 100%;
  height: 88rpx;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-button.disabled {
  background-color: #ccc;
  color: #999;
}

.submit-button:not(.disabled):active {
  background-color: #0056b3;
}
</style>
